﻿using Microsoft.Xna.Framework;

namespace Game500.Client.Src.Logic
{
  public class Camera2D
  {
    private readonly float myScreenHeight;
    private readonly float myScreenWidth;
    private Vector2 myLowerLeftConstraint;
    private Vector2 myPosition = Vector2.Zero;
    private Vector2 myUpperRightConstraint;

    public Camera2D(float screenWidth, float screenHeight)
    {
      myScreenWidth = screenWidth;
      myScreenHeight = screenHeight;
    }

    public float ScreenWidth
    {
      get { return myScreenWidth; }
    }

    public float ScreenHeight
    {
      get { return myScreenHeight; }
    }

    public Vector2 Position
    {
      get { return myPosition; }
      set { UpdatePosition(value); }
    }

    public Vector2 ConvertToScreenCoords(Vector2 vector)
    {
      return ConvertToScreenCoords(vector.X, vector.Y);
    }

    public Vector2 ConvertToScreenCoords(float x, float y)
    {
      return new Vector2(x - Position.X + myScreenWidth / 2, myScreenHeight - (y - Position.Y + myScreenHeight / 2));
    }

    private void UpdatePosition(Vector2 position)
    {
      if (position.X - ScreenWidth / 2 < myLowerLeftConstraint.X) myPosition.X = myLowerLeftConstraint.X + ScreenWidth / 2;
      else if (position.X + ScreenWidth / 2 > myUpperRightConstraint.X) myPosition.X = myUpperRightConstraint.X - (ScreenWidth / 2);
      else myPosition.X = position.X;

      if (position.Y - ScreenHeight / 2 < myLowerLeftConstraint.Y) myPosition.Y = myLowerLeftConstraint.Y + ScreenHeight / 2;
      else if (position.Y + ScreenHeight / 2 > myUpperRightConstraint.Y) myPosition.Y = myUpperRightConstraint.Y - ScreenHeight / 2;
      else myPosition.Y = position.Y;
    }

    public void SetConstrains(Vector2 lowerLeft, Vector2 upperRight)
    {
      myLowerLeftConstraint = lowerLeft;
      myUpperRightConstraint = upperRight;
    }
  }
}